﻿<template>
  <div class="residents-container">
    <el-dialog
      v-model="dialogObj.isDialogVisible"
      :title="dialogObj.editResidentsTitle"
      top="5vh"
      height="70vh"
      lock-scroll
      :width="1350"
      draggable
      class="res-add"
    >
      <!-- @open="fillData(dialogObj.editResidentsData)" -->
      <div class="add-health-manage p-10">
        <el-form :model="personInfo" :rules="rules">
          <el-row>
            <el-col :span="5">
              <el-form-item label="姓名" required prop="name">
                <el-input
                  disabled
                  v-model="personInfo.name"
                  placeholder="请输入姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="证件类型" prop="cardType" label-width="7em">
                <el-select
                  disabled
                  v-model="personInfo.cardType"
                  placeholder="请选择证件类型"
                  ref="cardTypeInput"
                >
                  <el-option label="居民身份证" value="居民身份证"></el-option>
                  <el-option
                    label="港澳台居民身份证"
                    value="港澳台居民身份证"
                  ></el-option>
                  <el-option
                    label="外国人永久居留身份证"
                    value="外国人永久居留身份证"
                  ></el-option>
                  <el-option
                    label="港澳台居民居住证"
                    value="港澳台居民居住证"
                  ></el-option>
                  <el-option label="居民户口本" value="居民户口本"></el-option>
                  <el-option label="护照" value="护照"></el-option>
                  <el-option label="军官证" value="军官证"></el-option>
                  <el-option label="文职干部证" value="文职干部证"></el-option>
                  <el-option label="士兵证" value="士兵证"></el-option>
                  <el-option label="驾驶执照" value="驾驶执照"></el-option>
                  <el-option label="出生证" value="出生证"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                  <el-option label="儿保卡" value="儿保卡"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="证件号码"
                required
                label-width="7em"
                prop="cardNumber"
              >
                <el-input
                  disabled
                  v-model="personInfo.cardNumber"
                  placeholder="请输入证件号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="出生日期"
                required
                label-width="7em"
                prop="birthday"
              >
                <el-date-picker
                  disabled
                  v-model="personInfo.birthday"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择出生日期"
                  :disabled-date="disableFutureDates"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-table
            class="mb-20"
            :data="questionTableData"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column
              v-for="(col, index) in dataCols"
              :align="index === 0 ? 'left' : 'center'"
              :prop="col.prop"
              :label="col.label"
              :key="col.prop + index"
            >
              <template #header="{ column }">
                <div v-html="column.label"></div>
              </template>
              <template #default="{ row, $index, column }">
                <template v-if="column.property === 'question'">
                  <div>( {{ $index + 1 }} ) {{ row.question }}</div>
                </template>
                <template v-else>
                  <div :key="index + Math.random()">
                    <el-radio
                      @click.native="radioChange(false)"
                      v-model="row.score"
                      :value="column.no"
                      ><span class="px-10">{{ column.no }}</span></el-radio
                    >
                  </div>
                  <div v-if="row.extraTip">
                    {{ row.extraTip[column.no - 1] }}
                  </div>
                </template>
              </template>
            </el-table-column>
          </el-table>

          <el-table
            :data="bodyTypeTableDataRender"
            :header-cell-class-name="headerCellClassFunc"
            border
            style="width: 100%"
          >
            <el-table-column
              v-for="(col, index) in bodyTypeCols"
              header-align="center"
              align="left"
              :prop="col.prop"
              :label="col.label"
              :key="index + col.prop"
            >
              <template #default="{ column, $index }">
                <div v-if="index === 0">
                  {{ leftLabels[$index] }}
                </div>
                <div v-else-if="$index === 0">
                  得分:
                  {{
                    bodyTypeDataObj[
                      `${column.property}${bodyTypebValKeys[$index]}`
                    ]
                  }}
                  <div v-if="$index === 0">
                    <el-radio-group
                      disabled
                      v-model="bodyTypeDataObj[`${column.property}Choice`]"
                    >
                      <el-radio value="1">是</el-radio>
                      <el-radio value="2">{{
                        index !== 9 ? "倾向是" : "基本是"
                      }}</el-radio>
                      <el-radio value="3">否</el-radio>
                    </el-radio-group>
                  </div>
                </div>
                <div v-else>
                  <el-checkbox-group
                    v-model="bodyTypeDataObj[`${column.property}Guidance`]"
                  >
                    <el-checkbox
                      v-for="(item, gIndex) in healthGuidance"
                      :key="item"
                      :label="gIndex + 1"
                      :value="gIndex + 1"
                    >
                      {{ item }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" size="large">取 消</el-button>
          <el-button type="primary" @click="saveData" size="large"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from "element-plus";
import http from "@/utils/request";
const disableFutureDates = (time) => time > new Date();
import {
  getDataCols,
  getQuestionTableData,
  getBodyTypeTableData,
  getBodyTypeCols,
  healthGuidance,
} from "@/pages/examples/addHealth/constants.js";
import { set } from "lodash";
export default {
  props: {
    dialogObj: {
      type: Object,
      default: () => ({
        isDialogVisible: false,
        editResidentsTitle: "",
        editResidentsData: {},
      }),
    },
  },
  data() {
    const validatorIdCard = (rule, value, callback) => {
      setTimeout(() => {
        //@ts-ignore
        const value2 = this.personInfo.cardNumber;
        if (value2 == "") {
          callback(new Error("请输入证件号码"));
          //@ts-ignore
        } else if (
          //@ts-ignore
          !/^\d{15}|^\d{17}[a-z]$/i.test(value2)
          //@ts-ignore
        ) {
          callback(new Error("请输入正确的证件号码"));
        } else {
          callback();
        }
      }, 200);
    };
    return {
      dataCols: getDataCols(),
      questionTableData: getQuestionTableData(),
      bodyTypeDataObj: getBodyTypeTableData().bodyTypeDataObj,
      bodyTypeTableDataRender: getBodyTypeTableData().bodyTypeTableDataRender,
      bodyTypeCols: getBodyTypeCols(),
      healthGuidance,
      redHeaderPropArr: [],
      valueArr: [],
      leftLabels: ["体质辨识", "中医药保健指导"],
      bodyTypebValKeys: ["Score", "Guidance"],
      personInfo: {
        name: "",
        cardNumber: "",
        birthday: "",
        cardType: "",
      },
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        cardNumber: [
          { required: true, validator: validatorIdCard, trigger: "blur" },
        ],
        birthday: [
          { required: true, message: "请选择出生日期", trigger: "blur" },
        ],
        cardType: [
          { required: true, message: "请选择证件类型", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    isDisableSave() {
      return !this.questionTableData.every((v) => v.score);
    },
    // bodyTypeDataObj 第一个key 生成的三个数据 仅用于展示文字，与需要提交的数据字段无关联因此不需要考虑
    bodyTypeDataKeys() {
      return Object.keys(this.bodyTypeDataObj).slice(3);
    },
  },
  methods: {
    disableFutureDates,
    // 回填数据
    fillData(obj) {
      console.log(obj);

      Object.keys(this.bodyTypeDataObj).forEach((key) => {
        const val = obj[key];
        // if (val) {
        //   this.bodyTypeDataObj[key] = val.split(",");
        // }
        if (key.includes("Guidance") && val) {
          this.bodyTypeDataObj[key] = val.split(",").map((v) => Number(v));
        }
      });
      this.questionTableData.forEach((row) => {
        const { questionId } = row;
        const newScore = obj[questionId] || 0;
        row.score = Number(newScore);
      });
      this.radioChange(true);
      this.personInfo = this.dialogObj.editResidentsData.personInfo;
    },
    radioChange(noGuidance) {
      const totalScoreMap = {};
      const { bodyTypeCols, bodyTypeDataObj, questionTableData } = this;
      const dataCols = bodyTypeCols.slice(1);
      dataCols.forEach((item) => {
        const { relateQuestions, prop, label } = item;
        const totalScore = questionTableData
          .filter((_v, index) => relateQuestions.includes(index + 1))
          .reduce((pre, cur) => {
            let { score } = cur;
            const isReverseScore = label === "平和质";
            if (isReverseScore) {
              score = score <= 0 ? 0 : 6 - score;
            }
            return pre + score;
          }, 0);
        totalScoreMap[prop] = totalScore;
        bodyTypeDataObj[`${prop}Score`] = totalScore;
      });
      const propArr = Object.keys(totalScoreMap);
      const valueArr = Object.values(totalScoreMap);
      let redHeaderPropArr = propArr.filter(
        (_v, index) => valueArr[index] >= 11
      );

      this.valueArr = valueArr;
      // ②除平和质外
      //  a.各体质类型得分相加之和≥11 分时，体质辨识选中“是”
      //  b.各体质类型得分相加之和为 9～10 分,体质辨识选中“倾向是”
      //  c.各体质类型得分相加之和≤8 分,体质辨识选中“否”
      // ③平和质对应选项其中，（2）（4）（5）（13）需反向计分，即选 1→5 分，选 2→4 分，
      // 选 3→3 分，选 4→2 分，选 5→1 分
      //  a.各问题得分相加之和≥17 分，同时其他 8 种体质得分均≤ 8 分，体质辨识选中“是”
      //  b.各问题得分相加之和≥17 分，同时其他 8 种体质得分≤10 分，体质辨识选中“基本是”
      //  d.不满足上述条件时，体质辨识选中“否”
      dataCols.forEach((item, curIndex) => {
        const { prop } = item;
        const otherScores = dataCols
          .filter((_v, index) => index !== curIndex)
          .map((v) => totalScoreMap[v.prop]);
        let choiceVal = "3";
        const curTotalScore = totalScoreMap[prop];
        const basicTotalScoreGt17 = curTotalScore >= 17;
        if (item.label === "平和质") {
          const isPhz = basicTotalScoreGt17 && otherScores.every((v) => v <= 8);
          const basiclyIsPhz =
            basicTotalScoreGt17 && otherScores.every((v) => v <= 10);
          choiceVal = isPhz ? "1" : basiclyIsPhz ? "2" : "3";
        } else {
          const conditionIs = curTotalScore >= 11;
          const conditionIsBasicly = curTotalScore >= 9;
          choiceVal = conditionIs ? "1" : conditionIsBasicly ? "2" : "3";
        }
        bodyTypeDataObj[`${prop}Choice`] = choiceVal;
      });
      bodyTypeDataObj.peacefulQualityChoice !== "1" &&
        (redHeaderPropArr = redHeaderPropArr.filter(
          (v) => v !== "peacefulQuality"
        ));
      this.redHeaderPropArr = redHeaderPropArr;
      let maxScore = 0;
      const allGuidance = healthGuidance.map((_v, index) => index + 1);
      const includePhz = bodyTypeDataObj.peacefulQualityChoice === "1";
      if (includePhz) {
        maxScore = Math.max(...valueArr);
      } else {
        maxScore = Math.max(...valueArr.slice(0, valueArr.length - 2));
      }
      !noGuidance &&
        dataCols.forEach((item) => {
          const { prop } = item;
          const choiceVal = bodyTypeDataObj[`${prop}Choice`];
          const curTotalScore = totalScoreMap[prop];
          if (curTotalScore === maxScore && choiceVal === "1") {
            bodyTypeDataObj[`${prop}Guidance`] = allGuidance;
          } else {
            bodyTypeDataObj[`${prop}Guidance`] = [];
          }
        });
    },
    //重置表单
    resetForm() {
      this.personInfo = {
        name: "",
        cardNumber: "",
        birthday: "",
        id: "",
      };
      this.bodyTypeDataObj = getBodyTypeTableData().bodyTypeDataObj; // 重置体质数据
      this.questionTableData.forEach((item) => (item.score = null)); // 清空问卷评分
      // 其他需要重置的状态
      this.radioChange();
    },

    saveData() {
      const {
        bodyTypeDataObj,
        questionTableData,
        personInfo,
        bodyTypeDataKeys,
      } = this;
      const submitObj = { ...personInfo };
      questionTableData.forEach((item) => {
        submitObj[item.questionId] = item.score;
      });
      bodyTypeDataKeys.forEach((key) => {
        submitObj[key] = bodyTypeDataObj[key];
        // 提交数据时，需要将checkbox数组转为字符串
        if (key.includes("Guidance")) {
          submitObj[key] = submitObj[key].join(",");
        }
      });
      console.log(submitObj);
      http.post("/healthManage/update", submitObj).then((res) => {
        if (res.code == 200) {
          ElMessage.success(res.message);
          this.resetForm();
          this.dialogObj.isDialogVisible = false;
          this.$emit("refreshData");
        }
      });
    },

    headerCellClassFunc({ column }) {
      const { property } = column;
      const { redHeaderPropArr, valueArr } = this;
      return redHeaderPropArr.includes(property) && valueArr.some(Boolean)
        ? "red-header-cell"
        : "";
    },
    //关闭弹窗
    closeDialog() {
      this.resetForm();
      this.dialogObj.isDialogVisible = false;
    },
  },
  watch: {
    dialogObj: {
      handler(val) {
        const { isDialogVisible, editResidentsData } = val;
        if (isDialogVisible) {
          this.fillData(editResidentsData);
        }
      },
      deep: true,
    },
  },
};
</script>
<style scoped>
.add-health-manage {
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
  -ms-overflow-style: none !important; /* 适用于IE和Edge */
  height: 500px;
}
:deep(.red-header-cell) {
  color: red !important;
}
:deep(.add-health-manage .el-form-item .el-select__wrapper) {
  width: 100%;
}
.p-10 {
  padding: 10px;
}
.mt-30 {
  margin-bottom: 30px;
}
.d-flex {
  display: flex;
}
.jc-between {
  justify-content: space-between;
}
.jc-center {
  justify-content: center;
}
.ai-center {
  align-items: center;
}
.px-10 {
  padding-left: 10px;
  padding-right: 10px;
}
.py-10 {
  padding: 10px 0;
}
.mb-20 {
  margin-bottom: 20px;
}
.text-center {
  text-align: center;
}
.text-left {
  text-align: left;
}
</style>
